package com.qxsx.midi.activity.home;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.activity.me.LoginActivity;
import com.qxsx.midi.activity.me.MeKejiantActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.Tools;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.utils.callBackNull;
import com.qxsx.midi.view.YYImageViwe;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Zrj on 2015/9/6.
 */
public class MusicDetailsActivity extends BaseActivity implements View.OnClickListener {
    private CustomProgress customProgress;

    private TextView tv_name, tv_price, tv_content;//名称，价格，内容
    private YYImageViwe iv_musicdeails;
    private Button btn_addorder, btn_buy, btn_chakan, btn_shiti;
    private String file_url = "";//PDF下载地址

    String id, type, buy;
    Dialog dialog;
    String login_name;
    String cover_img, name, price, introduction, order_code, order_id;
    String flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_musicdetails);
        setTitle("曲谱购买");
        setNavBtn(R.mipmap.back, 0);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");//得到ID
        type = intent.getStringExtra("type");
        buy = intent.getStringExtra("buy");
        customProgress = CustomProgress.show(MusicDetailsActivity.this, "正在加载中....", true, null);

        findById();
        musicdetails();
    }

    @Override
    protected void onResume() {
        super.onResume();
        login_name = (String) SPUtils.get(AppContext.getContext(), "login_name", "");

    }

    private void findById() {
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_price = (TextView) findViewById(R.id.tv_price);

        tv_content = (TextView) findViewById(R.id.tv_content);

        iv_musicdeails = (YYImageViwe) findViewById(R.id.iv_musicdeails);
        iv_musicdeails.setPadding(100, 10, 100, 10);

        btn_addorder = (Button) findViewById(R.id.btn_addorder);
        btn_addorder.setOnClickListener(this);
        btn_buy = (Button) findViewById(R.id.btn_buy);
        btn_buy.setOnClickListener(this);
        btn_chakan = (Button) findViewById(R.id.btn_chakan);
        btn_chakan.setOnClickListener(this);
        btn_shiti = (Button) findViewById(R.id.btn_shiti);
        btn_shiti.setOnClickListener(this);


        if (buy.equals("1")) {
            btn_addorder.setVisibility(View.GONE);
            btn_buy.setVisibility(View.GONE);
            btn_buy.setClickable(false);
            btn_addorder.setClickable(false);
            btn_shiti.setVisibility(View.GONE);
            btn_shiti.setClickable(false);
            btn_chakan.setVisibility(View.VISIBLE);
            btn_chakan.setClickable(true);
        } else {
            btn_addorder.setVisibility(View.VISIBLE);
            btn_buy.setVisibility(View.VISIBLE);
            btn_buy.setClickable(true);
            btn_addorder.setClickable(true);
            btn_chakan.setVisibility(View.GONE);
            btn_chakan.setClickable(false);
            btn_shiti.setVisibility(View.VISIBLE);
            btn_shiti.setClickable(true);
        }


    }

    /**
     * 页面
     */
    private void musicdetails() {

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();

        try {
            object.put("material_id", id);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("402", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    try {
                        JSONObject object1 = array.getJSONObject(0);
                        cover_img = object1.getString("cover_img");
                        name = object1.getString("name");
                        price = object1.getString("price");
                        introduction = object1.getString("introduction");
                        file_url = object1.getString("file_url");

                        MyNet.setNetImage(AppContext.getContext(), iv_musicdeails, cover_img);
                        tv_name.setText(name);
                        tv_price.setText(price);
                        tv_content.setText(introduction);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {

                    Log.e("code", code.toString());
                    Log.e("message", message.toString());

                }
                customProgress.dismiss();

            }
        });


    }

    /**
     * 订单
     */

    private void order() {
        customProgress = CustomProgress.show(MusicDetailsActivity.this, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String user_id = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        try {

            object.put("material_id", id);
            object.put("type", type);
            object.put("user_id", user_id);
            object.put("price", price);

            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("403", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if (code.toString().equals("200")) {
                    ShowToast("已收藏入我的订单");
                } else if (code.toString().equals("462")) {
                    ShowToast("该教材已收藏");
                }


                try {
                    JSONObject object1 = array.getJSONObject(0);
                    object1.getString("order_id");
                    object1.getString("order_code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();
            }
        });


    }


    /**
     * 支付的dialog
     */
    private void dialogbuy() {

        LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
        View view = layout.inflate(R.layout.dialog_buy_item, null);
        dialog = new AlertDialog.Builder(MusicDetailsActivity.this).create();

        TextView tv_weixin = (TextView) view.findViewById(R.id.tv_weixin);
        TextView tv_zhifu = (TextView) view.findViewById(R.id.tv_zhifu);

        tv_zhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.AliPayInfo info = new Tools.AliPayInfo("迷笛考级", name, price);
                Tools.WeiXinPayInfo info1 = new Tools.WeiXinPayInfo(order_code, (int) (Float.parseFloat(price) * 100), tv_name.getText().toString());
                info.OrderCode = order_code;
                Tools.Pay(info1, info, MusicDetailsActivity.this, "支付宝", new callBackNull() {
                            @Override
                            public void run() {
                                flag = "1";
                                wreslust();
                                dialog.dismiss();
                                btn_addorder.setVisibility(View.GONE);
                                btn_buy.setVisibility(View.GONE);
                                btn_buy.setClickable(false);
                                btn_addorder.setClickable(false);
                                btn_chakan.setVisibility(View.VISIBLE);
                                btn_chakan.setClickable(true);
                                //dialogfinish();
                            }
                        }, new callBackNull() {
                            @Override
                            public void run() {
                                flag = "0";
                                wreslust();
                                Toast.makeText(MusicDetailsActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        },
                        null
                );
            }
        });
        /**
         * 微信支付
         */
        tv_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Tools.AliPayInfo info = new Tools.AliPayInfo("迷笛考级", name, price);
                Tools.WeiXinPayInfo info1 = new Tools.WeiXinPayInfo(order_code, (int) (Float.parseFloat(price) * 100), tv_name.getText().toString());
                info.OrderCode = order_code;
                Tools.Pay(info1, info, MusicDetailsActivity.this, "微信", new callBackNull() {
                            @Override
                            public void run() {
                                flag = "1";
                                wreslust();
                                dialog.dismiss();
                                dialogfinish();
                            }
                        }, new callBackNull() {
                            @Override
                            public void run() {
                                flag = "0";
                                wreslust();
                                Toast.makeText(MusicDetailsActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        },
                        null
                );


            }
        });
        TextView tv_clance = (TextView) view.findViewById(R.id.tv_clance);
        tv_clance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int x = dm.widthPixels;// 屏幕的宽
        int y = dm.heightPixels;// 屏幕的宽
        dialog = new Dialog(MusicDetailsActivity.this, R.style.dialog);
        dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
        dialog.show();
        dialog.setContentView(view);
        dialog.setCancelable(false);


    }

    /**
     * 支付完成的dialog
     */
    private void dialogfinish() {
        LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
        View view = layout.inflate(R.layout.dialog_buy_finish, null);
        dialog = new AlertDialog.Builder(MusicDetailsActivity.this).create();
        Button btn_see = (Button) view.findViewById(R.id.btn_see);
        Button btn_clance = (Button) view.findViewById(R.id.btn_cancel);
        btn_clance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_see.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent it = new Intent(MusicDetailsActivity.this, MeKejiantActivity.class);
                it.putExtra("file_url", file_url);//传递商家ID
                MusicDetailsActivity.this.startActivity(it);
                dialog.dismiss();
            }
        });
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int x = dm.widthPixels;// 屏幕的宽
        int y = dm.heightPixels;// 屏幕的高
        dialog = new Dialog(MusicDetailsActivity.this, R.style.dialog_finish);
        dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
        dialog.show();
        dialog.setContentView(view);
        dialog.setCancelable(false);


    }

    /**
     * 订单
     */

    private void orderr() {
        customProgress = CustomProgress.show(MusicDetailsActivity.this, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String user_id = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        try {

            object.put("material_id", id);
            object.put("type", type);
            object.put("user_id", user_id);
            object.put("price", price);

            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("405", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                try {
                    JSONObject object1 = array.getJSONObject(0);
                    order_id = object1.getString("order_id");
                    order_code = object1.getString("order_code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();
                dialogbuy();
            }
        });


    }

    /**
     * 记录支付结果
     */
    private void wreslust() {
        customProgress = CustomProgress.show(MusicDetailsActivity.this, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();

        try {
            object.put("order_id", order_id);
            object.put("flag", flag);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("404", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                customProgress.dismiss();
            }
        });


    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_addorder:
                if (login_name != "") {
                    order();
                } else {
                    startActivity(new Intent(MusicDetailsActivity.this, LoginActivity.class));
                }
                break;


            case R.id.btn_buy:

//                if (login_name != "") {
//                    orderr();
//
//                } else {
//                    startActivity(new Intent(MusicDetailsActivity.this, LoginActivity.class));
//                }
                Toast.makeText(MusicDetailsActivity.this,"该功能暂时无法使用",Toast.LENGTH_SHORT).show();

                break;

            case R.id.btn_chakan:
                Intent it = new Intent(MusicDetailsActivity.this, MeKejiantActivity.class);
                it.putExtra("file_url", file_url);//传递PDF地址
                startActivity(it);
                break;

            case R.id.btn_shiti:
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("http://b.mashort.cn/h.6RWlJ?sm=5e0e71");
                intent.setData(content_url);
                startActivity(intent);
                break;


        }
    }
}
